//
//  CardView.swift
//  TanTan
//
//  Created by 于航 on 2024/9/15.
//

import SwiftUI

struct CardView: View {
    @EnvironmentObject var appState : AppState
    var catCard : CatCard
    var swipeAction: (() -> Void)?
    @State var index : Int = 0
    @State var offset: CGSize = .zero
    var body: some View {
        
        //显示图片
        GeometryReader { proxy in
            let frameWidth = proxy.size.width
            let frameHeight = proxy.size.height
            ZStack(alignment: .top) {
                Image(catCard.photos[index])
                    .resizable()
                    .frame(width: frameWidth, height: frameHeight)
                    .aspectRatio(contentMode: .fit)
                    .cornerRadius(appState.isFullScreen ? 0 : 20)
                
                //实现左右点击切换图片
                HStack {
                    //点击左边
                    Rectangle()
                        .onTapGesture {
                            updateImageIndex(hasMoreImage: false)
                        }
                    //点击右边
                    Rectangle()
                        .onTapGesture {
                            updateImageIndex(hasMoreImage: true)
                        }
                }
                .foregroundColor(.white.opacity(0.001))
                
                //上面切换图片的白条
                HStack {
                    ForEach(0..<catCard.photos.count, id: \.self) {
                        image in
                        RoundedRectangle(cornerRadius: 20)
                            .frame(height: 4)
                            .foregroundColor(self.index == image ? .white : .gray.opacity(0.3))
                    }
                }
                .padding(.top, 10)
                .padding(.horizontal)
                
                if !appState.isFullScreen {
                    VStack {
                        HStack {
                            if offset.width > 0 {
                                createCardLabel(title: "xmark.circle", degree: 20)
                                Spacer()
                            } else if offset.width < 0 {
                                Spacer()
                                createCardLabel(title: "heart.fill", degree: -20)
                            }
                        }
                        .padding(30)
                        
                        Spacer()
                        createCatCardBottomInfo()
                    }
                }
                
                

            }
            .offset(offset)
            .scaleEffect(getScaleAmount()) //放大缩小效果
            .rotationEffect(Angle(degrees: getRotationAmount()))
            .gesture(DragGesture()
                .onChanged { value in
                    if !appState.isFullScreen {
                        withAnimation(.easeOut(duration: 0.2)) {
                            offset = value.translation
                        }
                    }
                }
                .onEnded { value in
                    if !appState.isFullScreen {
                        withAnimation(.easeOut(duration: 0.2)) {
                            let screenCutOff = frameWidth / 2 * 0.8
                            let translation = value.translation.width
                            let checkingStatus = translation > 0 ? translation : -translation
                            if checkingStatus > screenCutOff {
                                offset = CGSize(width: (translation > 0 ? frameWidth : -frameWidth) * 5, height: value.translation.height)
                                swipeAction?()
                            } else {
                                offset = .zero
                            }
                        }

                    }
                }
            )
        }
    }
    
    func updateImageIndex(hasMoreImage : Bool) {
        let nextIndex = hasMoreImage ? index + 1 : index - 1
        index = min(max(0, nextIndex), catCard.photos.count - 1)
    }
    
    func getScaleAmount() -> CGFloat {
        let max = UIScreen.main.bounds.width / 2 //拿到屏幕宽度的一半
        let currentAmount = abs(offset.width)
        let percentage = currentAmount / max
        return 1 - min(percentage, 0.7) * 0.5
    }
    
    func getRotationAmount() ->Double {
        let max = UIScreen.main.bounds.width / 2
        let currentAmount = offset.width
        let percentage = currentAmount / max
        return Double(percentage * 10)
    }
    
    func createCardLabel(title : String, degree: Double) -> some View {
        Image(systemName: title)
            .foregroundColor(.red)
            .font(.largeTitle)
            .padding(.horizontal)
            .rotationEffect(Angle(degrees: degree))
    }
    
    func createCatCardBottomInfo() -> some View {
        HStack {
            VStack(alignment: .leading, spacing: 5) {
                Text("\(catCard.name), \(catCard.age)岁")
                    .font(.system(size: 30))
                    .fontWeight(.heavy)
                HStack {
                    Text("\(catCard.category)")
                        .font(.system(size: 20))
                        .frame(maxWidth: 80, maxHeight: 30)
                        .background(.white.opacity(0.3))
                        .cornerRadius(3)
                        .fontWeight(.bold)
                        .padding(5)
                    HStack {
                        Image(systemName: "location")
                        Text("\(catCard.address)")
                    }
                    .padding(0.1)
                }
            }
            Spacer()
            Button(action: {
                appState.isFullScreen = true
            }, label: {
                Image(systemName: "info.circle.fill")
                    .font(.system(size: 30))
                    .padding(8)
            })
        }
        .foregroundStyle(.white)
        .padding(10)
        .padding(.bottom, 60)
        .background(
            LinearGradient(colors: [.black.opacity(0.9), .clear], startPoint: .bottom, endPoint: .top))
        .cornerRadius(20)
        .clipped()
    }
}

#Preview {
    CardView(catCard : CatCard(name: "喵桑", age: 1, address: "小区花坛", category: "狮子猫", photos: ["Cat3", "Cat4"], info: "狮子猫是一种独特的猫品种，起源于中国山东临清，是波斯猫和中华田园鲁西狸猫杂交而成的品种。‌这种猫体型较大，略壮，脸宽而圆，嘴巴呈狐狸脸形状，耳朵短，直鼻梁，下巴强壮，眼睛多为双黄色、双蓝色或鸳鸯眼，四肢长短适中，爪子有长毛，毛长且大多为白色，也有花色毛。狮子猫性格活泼可爱，温顺聪明且粘人，能与陌生的同伴和谐相处。它们主要以鱼、虾、动物内脏和杂粮为食，需要定时、定量喂养，并添加适量的维生素和矿物质，同时给予足够的清水。狮子猫的繁殖性较差，每年一胎，每胎产仔2-3只。因其全身雪白、长毛和鸳鸯眼而被认为具有观赏价值。‌"))
        .environmentObject(AppState())
}
